#! /usr/bin/env python3

import logging
import pytest

import colorlog


class Log:
    logging.basicConfig(level=logging.INFO,
        format="%(asctime)s %(filename)12s line:[%(lineno)3d] [%(levelname)8s] %(message)s")

    def __init__(self):
        self.DEBUG = "\033[0;37m"
        self.INFO = "\033[0;32m"
        self.WARNING = "\033[0;33m"
        self.ERROR = "\033[0;31m"
        self.CRITICAL = "\033[1;31m"
        self.INIT = "\033[0m"

    def debug(self, msg):
        logging.debug(f'{self.DEBUG}{msg}{self.INIT}')
    def info(self, msg):
        logging.info(f'{self.INFO}{msg}{self.INIT}')

    def warning(self, msg):
        logging.warning(f'{self.WARNING}{msg}{self.INIT}')

    def error(self, msg):
        logging.error(f'{self.ERROR}{msg}{self.INIT}')

    def critical(self, msg):
        logging.critical(f'{self.CRITICAL}{msg}{self.INIT}')


class Logger:
    def __init__(self):
        color_config = {
            'DEBUG': 'white',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red'
        }
        # 设置日志
        self.logger = logging.getLogger('test')
        # 输出定向
        color_console_handler = logging.StreamHandler()
        console_handler = logging.StreamHandler()
        file_handler = logging.FileHandler(filename='0702.log', mode='w', encoding='utf-8')
        # 设置日志级别
        self.logger.setLevel(logging.DEBUG)
        color_console_handler.setLevel(logging.DEBUG)
        console_handler.setLevel(logging.DEBUG)
        file_handler.setLevel(logging.INFO)
        # 设置日志的格式
        color_console_formatter = colorlog.ColoredFormatter('%(log_color)s[%(asctime)s] %(levelname)8s line: %(lineno)3d %(message)s',
            datefmt = "%Y-%m-%d %H:%M:%S", log_colors = color_config)
        console_formatter = logging.Formatter('%(asctime)s %(filename)12s [%(lineno)3d] --> %(levelname)8s %(message)s')
        file_formatter = logging.Formatter('%(asctime)s %(pathname)22s %(levelname)8s %(message)s', datefmt = "%Y-%m-%d %H:%M:%S")

        # 将格式应用至对应的文件句柄上
        color_console_handler.setFormatter(color_console_formatter)
        console_handler.setFormatter(console_formatter)
        file_handler.setFormatter(file_formatter)

        if not self.logger.handlers:
            #self.logger.addHandler(console_handler)
            #self.logger.addHandler(file_handler)
            self.logger.addHandler(color_console_handler)

if __name__ == "__main__":
    #logger = Logger().logger
    
    log = Log()
    log.debug("这是一个debug级别的信息")
    log.info("这是一个info级别的信息")
    log.warning("这是一个warning级别的信息")
    log.error("这是一个error级别的信息")
    log.critical("这是一个critical级别的信息")
    """ 
    logger.debug('debug')
    logger.info('info')
    logger.warning('warning')
    logger.error('error')
    logger.critical('critical')
    """
